package com.tinem.platform.module.starter.web.config;

import com.tinem.platform.module.commons.util.EnvUtil;
import com.tinem.platform.module.starter.web.exception.JsonExceptionHandler;
import com.tinem.platform.module.starter.web.filter.GatewayFilter;
import com.tinem.platform.module.starter.web.filter.LogFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Date;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className WebConfig
 * @description TODO
 * @site 
 * @company 
 * @create 2020-07-03 14:50
 */
@Configuration
@SuppressWarnings("unchecked")
public class WebConfig implements WebMvcConfigurer {


    @Value("${info.artifactId}")
    String artifactId;
    @Value("${info.instance.name}")
    String instanceName;
    @Value("${spring.profiles.active}")
    String active;

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(String.class, Date.class,(value)->new Date(Long.parseLong(value)));
        registry.addConverter(Date.class, String.class,(value)->String.valueOf(value.getTime()));
    }

    @Bean
    public JsonExceptionHandler exceptionHandler(){
        return new JsonExceptionHandler();
    }

    @Bean
    public EnvUtil envUtil() {
        return new EnvUtil(active);
    }

    @Bean
    public FilterRegistrationBean gatewayFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setOrder(1);
        filterRegistrationBean.setFilter(new GatewayFilter());
        filterRegistrationBean.setName("GatewayFilter");
        filterRegistrationBean.addUrlPatterns("*.do","*.api","*.notify");
        return filterRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean logFilter(io.opentracing.Tracer tracer) {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setOrder(2);
        filterRegistrationBean.setFilter(new LogFilter(tracer,artifactId,instanceName));
        filterRegistrationBean.setName("LogFilter");
        filterRegistrationBean.addUrlPatterns("*.do","*.api","*.notify");
        return filterRegistrationBean;
    }
}
